<template>
  <div class="search-bar">
    <div class="xinzeng">
      <el-button type="text" @click="addShowInit()">
        <i class="fas fa-plus"></i>新增
      </el-button>
      <el-button type="text" @click="exportExcel">
        <i class="el-icon-download"></i>导出
      </el-button>
      <el-upload
        action
        :show-file-list="false"
        :on-change="importExcel"
        :auto-upload="false"
      >
        <el-button icon="upload" type="text" size="small">
          <i class="fas fa-file-import"></i>导入
        </el-button>
      </el-upload>
    </div>
    <!-- 数据渲染部分 -->
    <el-table
      :data="list"
      style="width: 100%"
      row-key="id"
      lazy
      :load="load"
      :tree-props="{ children: 'children', hasChildren: 'hasChild' }"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="名称">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="编码" fixed>
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.code }}</span>
        </template>
      </el-table-column>
      <el-table-column label="全名">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.fullname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否启用">
        <template slot-scope="scope">
          <span v-show="scope.row.isEnabled == '1'">是</span>
          <span v-show="scope.row.isEnabled != '1'">否</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            style="color: #1890ff"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <span style="color: #bbb; margin-right: 3px">|</span>
          <el-dropdown size="small">
            <span class="el-dropdown-link" style="color: #1890ff">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  style="color: rgba(0, 0, 0, 0.65); margin: 0 5px"
                  @click="handleAdds(scope.row)"
                >
                  添加下级
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  style="color: rgba(0, 0, 0, 0.65); margin: 0 5px"
                  @click="handleDelete(scope.row)"
                >
                  删除
                </el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增 -->
    <el-drawer
      :title="id ? '编辑' : '新增'"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose"
    >
      <el-form
        :model="listForm"
        :rules="rules"
        ref="listForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="父级" prop="pid">
          <el-select v-model="listForm.pid" placeholder="请选择父级" disabled>
            <el-option
              v-for="(item, index) in fuji"
              :key="index"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="listForm.code"></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="listForm.name"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="listForm.phone"></el-input>
        </el-form-item>
        <el-form-item
          label="是否启用"
          style="display: block; margin-bottom: 10px"
        >
          <el-select v-model="listForm.state" placeholder="请选择是否启用">
            <el-option
              v-for="(item, index) in enable"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="listForm.remark"></el-input>
        </el-form-item>
        <el-form-item label="创建人" prop="createBy">
          <el-input v-model="listForm.createBy" disabled></el-input>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            type="datetime"
            v-model="listForm.createTime"
            placeholder="选择创建时间"
            disabled
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="修改人" prop="updateBy">
          <el-input v-model="listForm.updateBy" disabled></el-input>
        </el-form-item>
        <el-form-item label="修改时间" prop="updateTime">
          <el-date-picker
            type="datetime"
            v-model="listForm.updateTime"
            placeholder="选择修改时间"
            disabled
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item class="btns">
          <el-button @click="resetForm('listForm')" style="margin-right: 10px"
            >取消</el-button
          >
          <el-button
            v-if="id"
            type="primary"
            style="background-color: #17b3a3; border: none"
            @click="editForm('listForm')"
            >确定</el-button
          >
          <el-button
            v-else
            type="success"
            style="background-color: #17b3a3; border: none"
            @click="addForm('listForm')"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </el-drawer>
    <!-- 添加下级 -->
    <el-drawer
      title="操作"
      :visible.sync="drawerFrom"
      :direction="direction"
      :before-close="handleClose"
    >
      <el-form
        :model="listForm"
        :rules="rules"
        ref="listForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="父节点" prop="pid" disabled>
          <el-input v-model="listForm.pid" disabled></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="listForm.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="listForm.code" disabled></el-input>
        </el-form-item>
        <el-form-item label="全名" prop="fullname">
          <el-input v-model="listForm.fullname" disabled></el-input>
        </el-form-item>
        <el-form-item
          label="是否启用"
          style="display: block; margin-bottom: 10px"
        >
          <el-select v-model="listForm.state" placeholder="请选择是否启用" disabled>
            <el-option
              v-for="(item, index) in enable"
              :key="index"
              :label="item.label"
              :value="item.value"
              disabled
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建人" prop="createBy">
          <el-input v-model="listForm.createBy" disabled></el-input>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            type="datetime"
            v-model="listForm.createTime"
            placeholder="选择创建时间"
            disabled
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="修改人" prop="updateBy">
          <el-input v-model="listForm.updateBy" disabled></el-input>
        </el-form-item>
        <el-form-item label="修改时间" prop="updateTime">
          <el-date-picker
            type="datetime"
            v-model="listForm.updateTime"
            placeholder="选择修改时间"
            disabled
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
    </el-drawer>
    <pagination
      :page="queryInfo.pageNo"
      :componentTotal="total"
      @changeRows="setPageSize"
      @changePage="setPageNo"
    ></pagination>
  </div>
</template>

<script>
import { Button } from "element-ui";
import axios from "axios";
import Pagination from "../Pagination.vue";
import { excelExportUseJson, excelImport } from "../../assets/js/xlsx";

export default {
  components: {
    "el-button": Button,
    Pagination,
  },
  data() {
    return {
      search1: "", // 用于存储编码
      search2: "", // 用于存储名称
      isExpanded: false, // 控制展开/收起的状态
      queryInfo: {
        _t: "",
        column: "createTime",
        order: "desc",
        field: "id,,name,code,phone,isEnabled_dictText,remark,action",
        pageNo: 1,
        pageSize: 10,
      },
      list: [],
      total: 0, // 用于存储总数
      loading: false, // 加载状态
      listHeader: {
        pid: "父级",
        hasChild: "是否有子节点",
        code: "编码",
        name: "名称",
        phone: "电话",
        isEnabled: "是否启用",
        remark: "备注",
        createBy: "创建人",
        createTime: "创建时间",
        updateBy: "修改人",
        updateTime: "修改时间",
      },
      listForm: {
        code: "",
        createBy: null,
        createTime: null,
        hasChild: "",
        id: "",
        isEnabled: "",
        isEnabled_dictText: "",
        name: "",
        phone: "",
        pid: "",
        remark: "",
        updateTime: null,
        updateBy: null,
        updateBy_dictText: "",
        version: "",
      },
      pid: "",
      drawer: false,
      drawerFrom: false,
      direction: "rtl",
      id: "",
      rules: {
        code: [{ required: true, message: "请输入仓库编码", trigger: "blur" }],
      },
      enable: [
        { label: "是", value: "1" },
        { label: "否", value: "0" },
      ],
      fuji: [],
    };
  },
  mounted() {
    this.getGongYing(); // 在组件加载时获取数据
    this.load();
  },
  methods: {
    // 添加下级
    async handleAdds(row) {
      this.listForm = { ...row };
      this.drawerFrom = true;
      this.id = row.id;
    },

    // 删除任务
    handleDelete(row) {
      console.log(row);
      this.$confirm("是否删除该条数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.deleteSamplereport(row.id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async deleteSamplereport(id) {
      await this.axios
        .delete(
          `http://8.142.74.15:48082/jeecg-boot/bas/basMaterialCategory/delete?id=${id}`
        )
        .then((res) => {
          console.log(res);
          this.getGongYing();
        })
        .catch((err) => {
          console.log(err);
          this.$message.error("删除失败，请重试。");
        });
    },
    // 查询父级
    getDonors() {
      this.axios
        .get("http://8.142.74.15:48082/jeecg-boot/sys/dict/loadTreeData")
        .then((res) => {
          this.fuji = res.data.result;
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
          this.$message.error("获取样本来源列表失败");
        });
    },
    // 添加任务
    addShowInit() {
      this.drawer = true;
      this.id = null;
      this.listForm = {
        code: "",
        createBy: null,
        createTime: null,
        hasChild: "",
        id: "",
        isEnabled: "",
        isEnabled_dictText: "",
        name: "",
        phone: "",
        pid: "",
        remark: "",
        updateTime: null,
        updateBy: null,
        updateBy_dictText: "",
        version: "",
      };
    },
    addForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (!valid) return false;
        await this.axios
          .post(
            "http://8.142.74.15:48082/jeecg-boot/bas/basMaterialCategory/add",
            this.listForm
          )
          .then((res) => {
            console.log(res);
            this.drawer = false;
            this.getGongYing();
          })
          .catch((err) => {
            console.log(err);
            this.$message.error("添加失败，请重试。");
          });
      });
    },
    // 编辑任务
    async handleEdit(row) {
      this.listForm = { ...row };
      this.drawer = true;
      this.id = row.id;
    },
    editForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (!valid) return false;
        await this.axios
          .put(
            "http://8.142.74.15:48082/jeecg-boot/bas/basMaterialCategory/edit",
            this.listForm
          )
          .then((res) => {
            console.log(res);
            this.drawer = false;
            this.getGongYing();
          })
          .catch((err) => {
            console.log(err);
            this.$message.error("编辑失败，请重试。");
          });
      });
    },
    // 取消重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.drawer = false;
    },
    // 导出
    exportExcel() {
      excelExportUseJson(this.list, this.listHeader, "仓库信息表");
    },
    // 导入
    importExcel(file) {
      console.log(file);
      excelImport(file.raw, "json").then((res) => {
        res = res.map((item) => {
          let newUserFrom = {};
          for (let [headerKey, headerVal] of Object.entries(this.listHeader)) {
            newUserFrom[headerKey] = item[headerVal];
          }
          newUserFrom.passWord = "123456";
          return newUserFrom;
        });
        console.log(res);
      });
    },
    // 查询列表tableData
    async getGongYing() {
      this.loading = true; // 设置加载状态
      this.queryInfo._t = new Date().getTime(); // 防止缓存
      try {
        const { data: res } = await axios.get(
          "http://8.142.74.15:48082/jeecg-boot/bas/basMaterialCategory/rootList",
          {
            params: this.queryInfo,
          }
        );

        if (res.code !== 200) {
          this.$message.error("获取任务管理列表失败");
          return;
        }
        this.list = res.result.records; // 获取记录
        this.total = res.result.total; // 获取总数
      } catch (error) {
        console.error("Error fetching data:", error);
        this.$message.error("请求数据失败，请重试。");
      } finally {
        this.loading = false; // 取消加载状态
      }
    },
    // 分页器
    setPageSize(val) {
      this.queryInfo.pageSize = val;
      this.getGongYing();
    },
    setPageNo(val) {
      this.queryInfo.pageNo = val;
      this.getGongYing();
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
        .catch(() => {});
    },
    toggleExpand() {
      this.isExpanded = !this.isExpanded; // 切换展开状态
    },
    async load(tree, treeNode, resolve) {
      this.queryInfo.pid = tree.id;
      const { data: res } = await axios.get(
        "http://8.142.74.15:48082/jeecg-boot/bas/basMaterialCategory/childList",
        {
          params: this.queryInfo,
        }
      );
      if (res.code !== 200) {
        return this.$message.error("获取子节点失败");
      }
      resolve(res.result);
    },
  },
};
</script>

<style scoped>
.search-bar {
  height: 100%;
  margin: 0;
  padding: 8px 24px;
  color: rgba(0, 0, 0, 0.65);
  font-size: 14px;
  list-style: none;
  background-color: #fff;
  transition: all 0.3s;
  border-radius: 2px;
}

.select-bar {
  display: flex;
  align-items: center;
}

.select-item {
  display: flex;
  align-items: center;
  padding: 0 12px;
  width: 384px;
}

label {
  width: 49px;
  color: #000;
  margin-right: 8px;
}

.input-field {
  width: 335px;
  height: 22px;
  padding: 4px 11px;
  border-radius: 5px;
  border: 1px solid #d9d9d9;
  transition: border-color 0.3s; /* 边框颜色变化过渡 */
  outline: none; /* 移除默认轮廓 */
}

/* 输入框鼠标悬停效果 */
.input-field:hover {
  border-color: #409eff; /* 悬停时边框颜色 */
}

/* 输入框获得焦点时的样式 */
.input-field:focus {
  border-color: #409eff; /* 焦点时边框颜色 */
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.5); /* 焦点时阴影 */
}

/* 按钮样式 */
.search-button,
.reset-button,
.toggle-button,
.submit-button {
  padding: 10px 15px; /* 内边距 */
  border-radius: 4px; /* 圆角 */
  transition: background-color 0.3s; /* 背景颜色变化过渡 */
}

/* 查询按钮 */
.search-button {
  background-color: #409eff; /* 主色调 */
  color: white; /* 字体颜色 */
  border: 1px solid #409eff;
  width: 82px;
  height: 32px;
  line-height: 12px;
}

/* 查询按钮悬停效果 */
.search-button:hover {
  background-color: #66b1ff; /* 悬停时背景色 */
  border-color: #66b1ff;
}

/* 重置按钮 */
.reset-button {
  background-color: #fff; /* 重置按钮背景 */
  color: rgba(0, 0, 0, 0.65); /* 字体颜色 */
  border: 1px solid #d9d9d9;
  width: 82px;
  height: 32px;
  line-height: 12px;
  margin-left: 8px;
  padding: 0 15px;
  transition: all 0.3s;
}

/* 重置按钮悬停效果 */
.reset-button:hover {
  background-color: #e6f7ff; /* 悬停时背景色 */
  border-color: #409eff;
  color: #409eff;
}

/* 提交按钮 */
.submit-button {
  background-color: #fff; /* 提交按钮背景 */
  color: rgba(0, 0, 0, 0.65); /* 字体颜色 */
  border: 1px solid #d9d9d9;
  width: 82px;
  height: 32px;
  line-height: 12px;
  margin-left: 8px;
  padding: 0 15px;
  transition: all 0.3s;
}

/* 提交按钮悬停效果 */
.submit-button:hover {
  background-color: #e6f7ff; /* 悬停时背景色 */
  border-color: #409eff;
  color: #409eff;
}

/* 图标样式 */
.search-button i,
.reset-button i,
.toggle-button i,
.submit-button i {
  margin-right: 5px; /* 图标与文本之间的间距 */
}
.toggle-button {
  border: none;
  background-color: #fff;
  color: #409eff;
}
/* xinzeng */
.xinzeng {
  display: flex;
  width: 300px;
  align-items: center;
}
.el-button {
  margin-right: 10px;
}
.el-button i {
  margin-right: 5px;
}
.shanchu:hover {
  background-color: #096ba0;
  color: #096dd9;
}
/* 展开内容的样式 */
/*.expand-content {
      margin-top: 10px;
      padding: 10px;
      border: 1px solid #d9d9d9;
      border-radius: 4px;
      background-color: #f9f9f9;
    } */
</style>
